<?php
if (!defined('PLUGINFRAME'))exit('hacking attempt');
class CommonModel{
    
    protected $record=2;
    private static $connected=false;
    private static $_conn=null;
    protected $_table='';
    public $_phtml=array();
    
    public  function __construct(){
        global $cfg;
        $this->_table=$cfg['db_pre'].strtolower(get_class($this));
        if (!self::$connected){
          $conn=mysql_connect($cfg['db_host'],$cfg['db_user'],$cfg['db_pwd']);
          if (!$conn)
             throw new Exception('连接失败!');
          if (!mysql_select_db($cfg['db_name'],$conn))
             throw new Exception('数据库不存在！');
          if (!mysql_query('SET NAMES '.$cfg['db_charset'],$conn))
             throw new Exception('数据库字符设置不对');
          self::$connected=true;
          self::$_conn=$conn;
        }
    }
    
    public function query($qstr){//debug_print_backtrace();echo "\r\n|".$qstr."|\r\n";
        global $lang;
        $sql=trim($qstr);
        $res=null;
        if (!$res=mysql_query($sql,self::$_conn))
           throw new Exception($lang['SQL_SYNTAX_ERROR']);
        return @mysql_num_rows($res)?$res:false;
    }
    
    
    public function select($scondition){
//        $sres=null;
        $result=array();
        $cdn=$scondition;
        isset($cdn['limit']) || $cdn['limit']=true;
        if (is_array($cdn)){
            if (isset($cdn['where']))
                $cdn['where']=$this->_where($cdn['where']);
            if (isset($cdn['field']))
                $cdn['field']=$this->_field($cdn['field']);
            if (isset($cdn['order']))
                $cdn['order']=$this->_order($cdn['order']);
//            if (isset($cdn['limit']))
//                $str.=$this->_limit($cdn['limit']);
            
        }
        $cdn['field']=empty($cdn['field'])?'*':$cdn['field'];
        $cdn['where']=empty($cdn['where'])?'':$cdn['where'];
        $cdn['order']=empty($cdn['order'])?'':$cdn['order'];
        $page=isset($_GET['page'])?$_GET['page']:1;
        $rStart=$page==1?0:($page-1)*$this->record;
        if ($cdn['limit'])
          $sSql='select '.$cdn['field'].' from '.$this->_table.' '.$cdn['where'].' '.$cdn['order'].' limit '.$rStart.' ,'.$this->record;
        else
          $sSql='select '.$cdn['field'].' from '.$this->_table.' '.$cdn['where'].' '.$cdn['order'];
        //echo $sSql;
        $count=0;
        if($cres=$this->query('select count(*) from '.$this->_table.' '.$cdn['where'])){
            $count=mysql_fetch_array($cres);
            $count=(int)array_shift($count);
        }
        $pages=ceil($count/$this->record);//总页数
        $url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?");
        $parse = parse_url($url);
        if(isset($parse['query'])) {
            parse_str($parse['query'],$params);
            unset($params['page']);
            $url   =  $parse['path'].'?'.http_build_query($params);
        }
        $pStart=(int)floor($page/6);
        $pStart=$pStart==0?1:$pStart*6;
        $pEnd=($pStart+6)>$pages?$pages:($pStart+6);
        for ($i=$pStart;$i<=$pEnd;$i++){
            $this->_phtml['page'][$i]=$url.'&page='.$i;
        }
        $this->_phtml['up']=$url.'&page='.($page==1?1:$page-1);
        $this->_phtml['down']=$url.'&page='.($page==$pages?$pages:$page+1);
        
        if ($sres=$this->query($sSql)){
            while ($row=mysql_fetch_array($sres))
               $result[]=$row;
        }
        return $result;
    }
    
    private function _where($wcondition){
        $cdn=$wcondition;
        $result='';
        if (is_string($cdn)){
            return ' where '.$this->escapeSql($cdn);
        }elseif (is_array($cdn)){
            $str='';
            foreach ($cdn as $cKey=>$cVal){
                $str && $str.=' and '.$cKey.' '.(strpos($cVal, 'in')===false?'='.(is_numeric($cVal)?$cVal:'"'.$cVal.'"'):$cVal);
                $str || $str=$cKey.' '.(strpos($cVal, 'in')===false?'='.(is_numeric($cVal)?$cVal:'"'.$cVal.'"'):$cVal);
            }
            $result=' where '.$this->escapeSql($str);
        }
        return $result;
    }
    
    private function _field($fields){
        $field=$fields;
        $result='';
        if (is_string($field)){
            return $field;
        }elseif (is_array($field)){
            $str='';
            foreach ($field as $fKey=>$fVal){
                $str && $str.=' , '.$fVal;
                $str || $str=$fVal;
            }
            $result=$str;
        }
        return $result;
    }
    
    private function _order($orders){
        $order=$orders;
        $result='';
        if (is_string($order)){
            return ' order by '.$order;
        }elseif (is_array($order)){
            $str='';
            foreach ($order as $oKey=>$oVal){
                $str && $str.=' ,'.$oKey.' '.$fVal;
                $str || $str=$oKey.' '.$oVal;
            }
            $result=$str;
        }
        return ' order by '.$result;
    }
    
/*    private function _limit($orders){
        $order=$orders;
        $result='';
        if (is_string($order)){
            return $order;
        }elseif (is_array($order)){
            $str='';
            foreach ($order as $oKey=>$oVal){
                $str && $str.=' ,'.$oKey.' '.$fVal;
                $str || $str=$oKey.' '.$oVal;
            }
            $result=$str;
        }
        return $result;
    }*/
    
    
    private function escapeSql($condition){
           return mysql_escape_string($condition);
    }
    
    public function count($csql){
        $csql=trim($csql);
        $result=0;
        if ($csql){
            if ($res=$this->query($csql))
              $result=array_shift(mysql_fetch_array($res));
        }
        return $result;
    }
    
    
    public function table($name=''){
        global $cfg;
        return empty($name)?$cfg['db_pre'].strtolower(get_class($this)):$cfg['db_pre'].$name;
    }

   public function getCategoryList(){
       global $cfg;
       $result=array();
       if ($cfg['memcache']){
           
       }else{
           $categorys=$this->query('select * from '.$this->table('category').' where delFlag=0');
           while ($row=mysql_fetch_assoc($categorys)){
               $result[$row['cateId']]=$row['parentId'];
           }
           return $result;
       }
   }

   public function old_timey($cid){
       $result='';
       if ($cid){
           $qStatus=$this->query('select * from '.$this->table().' where parentId='.$cid);
           if ($qStatus){
               while ($row=mysql_fetch_assoc($qStatus)){
                   $result[$row['cateId']]=$row['cateName'];
               }
           }
       }
       return $result;
   }


















}